//
//  DownloadManageViewController.m
//  SXH
//
//  Created by 房 国生 on 15/8/3.
//  Copyright (c) 2015年 lyss. All rights reserved.
//
#define PARK_VERSION @"/parksource/versionMatch"
#import "DownloadManageViewController.h"
#import "DownloadManagerTableViewCell.h"
#import "CommonService.h"
#import "DBManager.h"
#import "JSONModel.h"
#import "DXAlertView.h"
#import "TCBlobDownloadManager.h"
#import "SVProgressHUD.h"
#import "OpenUDID.h"
#import "ZipArchive.h"
#import "DownLoadModel.h"
#import "CheckVersionManager.h"
#import "WrapperViewController.h"
@interface DownloadManageViewController ()<DownloadManagerDelegate, UIActionSheetDelegate>{
    NSMutableArray *modelArray;
    ParkEntity *parkEntity;
}

@property (nonatomic, strong) IBOutlet UITableView *tableViewDownload;
@property (nonatomic, assign )BOOL downloading;
@end

@implementation DownloadManageViewController
@synthesize tableViewDownload;

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tableViewDownload registerClass:[RMSwipeTableViewCelliOS7UIDemoTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.navigationItem setTitle:NSLocalizedString(@"我的足迹", nil)];
    NSString *str = [[NSString alloc] init];
  
    modelArray = [NSMutableArray array];

    _messagesArray = [DBManager selectAllDownloadPark];
    if (_messagesArray) {
        for (int i =0 ; i<[_messagesArray count]; i ++) {
            ParkEntity *entiy = _messagesArray[i];
            
            if ([str isEqualToString:@""]) {
                str = entiy.ID;
            }else{
                str = [NSString stringWithFormat:@"%@,%@",str,entiy.ID];
            }
        }
        [self initNetWorkWithVersion:str];
    }
}
-(void)initNetWorkWithVersion:(NSString *)str
{
    NSDictionary * parm = [NSDictionary dictionaryWithObjectsAndKeys:str,@"parkidList", nil ];
    CommonService *service = [[CommonService alloc] init];
    [SVProgressHUD show];
    [service getNetWorkData:parm Path:PARK_VERSION Successed:^(id entity) {
        NSDictionary * dict = (NSDictionary *)entity;
        NSArray * arrayList = [dict objectForKey:@"rows"];
        for (int i = 0; i<arrayList.count; i++) {
            DownLoadModel *model =[[DownLoadModel alloc] initWithDictionary:arrayList[i] error:nil];
            [modelArray addObject:model];
            [tableViewDownload reloadData];
    }
          [SVProgressHUD dismiss];
    } Failed:^(NSInteger errorCode, NSString *message) {
        [self showLoadingView:NO];
    }];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.messagesArray count];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *couponTableViewCellIdentifier=@"DownloadManagerTableViewCell";
    DownloadManagerTableViewCell *cell = (DownloadManagerTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"DownloadManagerTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        //cell.delegate = self;
    }
    
    ParkEntity *entity = [self.messagesArray objectAtIndex:indexPath.row];
    //
    for (int i =0 ; i<[modelArray count]; i ++) {
        DownLoadModel * model = modelArray[i];
        if ([model.park_id isEqualToString:entity.ID]) {
            if (![model.version isEqualToString:entity.source_version]) {
                cell.labelNew.hidden = NO;
            }else{
                cell.labelNew.hidden = YES;
            }
        }
    }
    cell.labelTitle.text = entity.title;
    
    //读取文件夹的大小
    cell.labelSize.text = entity.package_size;
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 40;
}

- (void) delegateResouce:(NSInteger)tag {
}

#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ParkEntity *entity = [self.messagesArray objectAtIndex:indexPath.row];
     parkEntity = entity;
    for (int i =0 ; i<[modelArray count]; i ++) {
        DownLoadModel * model = modelArray[i];
        if ([model.park_id isEqualToString:entity.ID]) {
            if (![model.version isEqualToString:entity.source_version]) {
                UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"资源包操作" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"前往",@"更新", @"删除" ,nil];
                actionSheet.tag = indexPath.row;
                [actionSheet showInView:self.view];
            }else{
//                UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"资源包操作" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除" otherButtonTitles:@"前往更新", nil];
                UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"资源包操作" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"前往",@"删除" , nil];
                actionSheet.tag = indexPath.row;
                [actionSheet showInView:self.view];
            }
        }
    }

   
    
}

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    ParkEntity *entity = [self.messagesArray objectAtIndex:actionSheet.tag];
    if (buttonIndex == 0) {
        WrapperViewController *mvc = [[WrapperViewController alloc]init];
        ParkEntity *park = [[ParkEntity alloc]init];
        park.ID = entity.ID;
        mvc.parkEntity = park;
        [self.navigationController pushViewController:mvc animated:YES];
        //goto

        
        
            }
    else if (buttonIndex == 1){
        if (actionSheet.numberOfButtons > 3)
        {
            [self loadSpotDataWithParkId:entity.ID];
        }
        else
        {
            [DBManager createTable];
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
            NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
            NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",entity.ID ];
            NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
            
            if ([DBManager delegateItem:entity] == NO || [fileManager removeItemAtPath:park_path error:nil] == NO) {
                ALERT_ERR_MSG(@"资源包删除失败");
            } else {
                ALERT_ERR_MSG(@"资源包删除成功");
                [self.messagesArray removeObjectAtIndex:actionSheet.tag];
                [[CheckVersionManager sharedCheckVersionManager]relaodCheckManager];
                [[NSNotificationCenter defaultCenter]postNotificationName:Notification_findmeVC_refresh object:nil];
                [self.tableViewDownload reloadData];
            }

                   }
    }
    else if(buttonIndex == 2)
    {
        if (actionSheet.numberOfButtons > 3)
        {
            [DBManager createTable];
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
            NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
            NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",entity.ID ];
            NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
            
            if ([DBManager delegateItem:entity] == NO || [fileManager removeItemAtPath:park_path error:nil] == NO) {
                ALERT_ERR_MSG(@"资源包删除失败");
            } else {
                ALERT_ERR_MSG(@"资源包删除成功");
                [self.messagesArray removeObjectAtIndex:actionSheet.tag];
                [[CheckVersionManager sharedCheckVersionManager]relaodCheckManager];
                [[NSNotificationCenter defaultCenter]postNotificationName:Notification_findmeVC_refresh object:nil];
                [self.tableViewDownload reloadData];
            }

        }
    }
    DebugLog(@"buttonIndex = %ld", buttonIndex);
}

// Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.
// If not defined in the delegate, we simulate a click in the cancel button
- (void)actionSheetCancel:(UIActionSheet *)actionSheet {
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"DownloadManageViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"DownloadManageViewController"];
}
- (BOOL) loadSpotDataWithParkId:(NSString *)park_id {
    [self downloadPackage:park_id];
    return YES;
}
- (void) downloadPackage:(NSString *)park_id {
    

 
    NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
    NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
    NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",park_id ];
  
    NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
 
    
  
    //判断是否链接LET-FI设备，并试图读取SD卡上的相关内容
    NSString *LET_FI_URL = [NSString stringWithFormat:@"%@/resource/park-%@.zip", LET_FI, park_id];
    
    
    [self downloadPackage:LET_FI_URL ParkPath:park_path];

}
- (BOOL) downloadPackage:(NSString *)url ParkPath:(NSString *)park_path{
    return [[TCBlobDownloadManager sharedDownloadManager] startDownloadWithURL:[NSURL URLWithString:url]
                                                 customPath:park_path
                                              firstResponse:^(NSURLResponse *response) {
                                                  
                                              }
                                                   progress:^(float receivedLength, float totalLength) {
                                                       _downloading = YES;
                                                       NSLog(@"totalBytesRead = %f totalBytesExpectedToRead = %f",receivedLength,totalLength);
                                                       float progress = receivedLength / (float)totalLength;
                                                      
                                                       [SVProgressHUD showProgress:progress status:@"下载中..." maskType:SVProgressHUDMaskTypeNone];
                                                         parkEntity.package_size = [NSString stringWithFormat:@"%fM", totalLength/(1024.0*1024)];
                                                   }
                                                      error:^(NSError *error) {
    
                                                          _downloading = NO;
                                                          NSLog(@"error = %@",error);
                                                          
                                                          if ([url containsString:LET_FI] == YES) {
                                                              UserEntity *user = [UserEntity sharedInstance];
                                                              LocationManagement *lm = [LocationManagement sharedInstance];
                                                              NSString *longitude = [NSString stringWithFormat:@"%f", lm.location.coordinate.longitude ];
                                                              NSString *latitude = [NSString stringWithFormat:@"%f", lm.location.coordinate.latitude ];
                                                               NSString *url2 = @"";
                                                              if (parkEntity.isSpot) {
                                                                  url2 = [NSString stringWithFormat:@"%@%@?parkid=%@&userid=%@&longitude=%@&latitude=%@&phone_guid=%@&simple=%@",
                                                                          BASEURL, PARK_SOURCE, parkEntity.ID, user.userId, longitude, latitude, [OpenUDID value] ,@"0" ];
                                                              }else{
                                                                  
                                                                  url2 = [NSString stringWithFormat:@"%@%@?parkid=%@&userid=%@&longitude=%@&latitude=%@&phone_guid=%@&simple=%@",
                                                                          BASEURL, PARK_SOURCE, parkEntity.ID, user.userId, longitude, latitude, [OpenUDID value], @"1"];
                                                              }
                                                              if ([url isEqualToString:url2]) {
                                                                  ALERT_ERR_MSG(@"该景区暂无离线音频");
                                                              }
                                                              else
                                                              {
                                                                  [self downloadPackage:url2 ParkPath:park_path];
                                                                  _downloading = YES;
                                                              }
                                                              
                                                              
                                                              
                                                          } else {
                                                              ALERT_ERR_MSG(DownloadWebsiteSourceFail);
                                                          }
                                                      }
                                                   complete:^(BOOL downloadFinished, NSString *pathToFile) {
                                                      
                                                     
                                                      
                                                       //定义一个布尔类型的对象
                                                       BOOL ifsucess;
                                                       //在objective－c种，正确是YES 错误是NO
                                                       ifsucess = NO;
                                                    
                                                       NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:pathToFile];
                                                       NSData *data = [file readDataToEndOfFile];//得到xml文件
                                                       //对布尔型对象进行判断
                                                       if(data) {
                                                           NSLog(@"create file sucess");
                                                           //we need save this data to the sqlite
                                                           parkEntity.local_path = pathToFile;
                                                           
                                                           //解压压缩包
                                                           ZipArchive *za = [[ZipArchive alloc] init];
                                                           if ([za UnzipOpenFile: pathToFile]) {
                                                               BOOL ret = [za UnzipFileTo:park_path overWrite: YES];
                                                               if (NO == ret){
                                                                   NSLog(@"za UnzipFileTo fail");
                                                                   ALERT_ERR_MSG(@"解压失败");
                                                               } else {
                                                                   
                                                                   [SVProgressHUD showSuccessWithStatus:@"下载成功"];
                                                                   
                                                                   //删除压缩包文件
                                                                   [CommonService deleteFile:pathToFile];
                                                                   //获取文件夹的大小
                                                                   parkEntity.package_size = [CommonService getFolderSize:parkEntity.ID];
                                                                   [[DBManager createDataBase] open];
                                                                   parkEntity = [DBManager selectParkByParkId:parkEntity.ID];
                                                                  
                                                                   for (int i =0 ; i<[modelArray count]; i ++) {
                                                                       DownLoadModel * model = modelArray[i];
                                                                       if([parkEntity.ID isEqualToString:model.park_id]){
                                                                           parkEntity.source_version = model.version;
                                                                           break;
                                                                       }
                                                                   }
                                                                   [DBManager UpdataParkEntity:parkEntity];
                                                                   [[CheckVersionManager sharedCheckVersionManager]relaodCheckManager];
                                                                   [[NSNotificationCenter defaultCenter]postNotificationName:Notification_findmeVC_refresh object:nil];
                                                                   [self viewDidLoad];
//                                                                   CommonService *service = [[CommonService alloc] init];
//                                                                   if ([service getSpotDataFromLocal:self.parkId
//                                                                                           ArraySpot:arraySpot
//                                                                                       ArrayBusiness:arrayBusiness
//                                                                                         ArrayToilet:arrayToilet
//                                                                                       ArrayRoadLine:arrayRoadLine
//                                                                                          ParkEntity:parkEntity] == YES) {
//                                                                       ALERT_ERR_MSG(@"景区资料下载完成");;
//                                                                   } else {
//                                                                       ALERT_ERR_MSG(@"加载本地资源失败");
//                                                                   }
                                                               }
                                                               [za UnzipCloseFile];
                                                           } else {
                                                               
                                                           }
                                                       } else {
                                                           if ([url containsString:LET_FI] != YES) {
                                                               ALERT_ERR_MSG(DownloadFail);
                                                           }
                                                       }
                                                       _downloading = NO;
                                                   }];
}




@end
